package il.technion.cs236369.proxy;

import java.io.IOException;
import java.net.Socket;

import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.impl.DefaultHttpClientConnection;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.params.SyncBasicHttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpRequestExecutor;
import org.apache.http.protocol.ImmutableHttpProcessor;

/**
 *	The class in charge of sending requests on behalf of the proxy 
 *
 */
public class HttpClient
{
	private Socket m_socket;

	private HttpResponse m_response;
	private byte[] m_data;
	
	public HttpClient() 
	{
		m_response = null;
	}
	
	public HttpResponse GetLastResponse() 
	{
		return m_response;
	}

	public byte[] GetLastData() 
	{
		return m_data;
	}

 	public void CloseConnection()
 	{
		try 
		{
			m_socket.close();
			m_socket = null;
		} 
		catch (IOException e) 
		{
			System.err.println("Client couldn't close connection.");			
			e.printStackTrace();
		}
	}
	
 	/**
 	 * Sends out the request using the given connection and socket.
 	 * 
 	 * @param socket the socket to use for the connection
 	 * @param connection the connection through which to send the request
 	 * @param request the request to send
 	 * @return the response given
 	 */
	public HttpResponse SendRequest(Socket socket, 
									DefaultHttpClientConnection connection, 
									HttpRequest request)
									throws IOException, HttpException 
	{
		try
		{
			// prep the protocol
			HttpParams params = new SyncBasicHttpParams();
			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
			HttpProtocolParams.setContentCharset(params, "UTF-8");
			HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
			HttpProtocolParams.setUseExpectContinue(params, true);
	
			// and other necessities
			HttpProcessor processor = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {});
			HttpRequestExecutor executor = new HttpRequestExecutor();
			HttpContext context = new BasicHttpContext(null);
	
			// setup connection and request
			context.setAttribute(ExecutionContext.HTTP_CONNECTION, connection);
			connection.bind(socket, params);
			request.setParams(params);
			executor.preProcess(request, processor, context);
	
			// send the request and return the response
			return executor.execute(request, connection, context);
		}
		catch(Exception e)
		{
			System.err.println("Client couldn's send request.");
			e.printStackTrace();
		}
		
		return null;
	}

}
